/*
 * @Description:
 * @Author: william
 * @Date: 2025-07-09 15:47:10
 * @LastEditors: william
 * @LastEditTime: 2025-09-23 11:53:59
 */
// src/store/recipe.js
import { scheduler } from '@/utils/scheduler.js'

export const useRecipeStore = defineStore(
  'recipe',
  () => {
    const recipeLibraryList = ref([]) // 菜谱库(包括收藏)的菜谱列表
    const recipeFormulatingList = ref([]) // 调制中的菜谱列表
    const recipeCategoryList = ref([]) // 菜谱类别列表数据
    const recipeTempData = ref({}) // 手动操作时临时菜谱
    const recipeTasteOptions = ref([]) // 菜谱口味
    const recipeCookStyleOptions = ref([]) // 菜谱菜系
    const recipeWeightOptions = ref([]) // 菜谱份量
    const countryList = ref([]) // 适用国家
    const materialProcessDropList = ref([]) // 食材工艺列表

    watch(
      () => recipeLibraryList.value,
      (nv, ov) => {
        console.log('recipeLibraryList.value', nv, ov)
        if (nv.length) {
          // 上报菜谱信息，只上报菜谱库的菜谱
          nextTick(async () => {
            // const { code } = await g_api.user.apiCheckNetwork()
            // if (code !== 200) return
            // const { userInfo } = useUserStore()
            // const list = g_.cloneDeep(nv)
            // const appId = g_utils.getAppId()
            // const recipeList = list.map(item => {
            //   // console.log('item', item)
            //   item.appId = appId
            //   item.userId = userInfo.userId
            //   item.tenantId = userInfo.tenantId
            //   // 修改菜谱的头像
            //   item.picturePath = item.base64Image ? '' : item.picturePath
            //   item.base64Image = item.base64Image.replace(
            //     /^data:image\/[a-z]+;base64,/,
            //     ''
            //   )
            //   return item
            // })
            // g_api.recipe.apiUploadRecipeInfo({
            //   recipeList: recipeList,
            //   showToast: false
            // })
          })
        }
      },
      {
        deep: true
      }
    )

    const startCipeScheduler = (time = 1000 * 10) => {
      // 增加菜谱绑定数据上传任务
      scheduler.schedule(
        '菜谱列表数据上传定时任务',
        async () => {
          console.log('执行菜谱列表数据上传定时任务')
          const { code } = await g_api.user.apiCheckNetwork()
          if (code !== 200) return
          // 菜谱列表数据
          if (recipeLibraryList.value.length > 0) {
            const { userInfo } = useUserStore()
            const appId = g_utils.getAppId()
            const recipeList = recipeLibraryList.value.map(item => {
              return {
                ...item,
                appId,
                userId: userInfo.userId,
                tenantId: userInfo.tenantId,
                picturePath: item.base64Image ? '' : item.picturePath,
                base64Image: item.base64Image.replace(
                  /^data:application\/.+;base64,/,
                  ''
                )
              }
            })
            g_api.recipe.apiUploadRecipeInfo({
              recipeList,
              showToast: false
            })
          }
        },
        time
      ) // 每30分钟执行一次
    }
    
    
    

    const setRecipeCategoryList = _ => {
      return g_api.recipe
        .apiQueryIngredientList({
          model: '',
          showToast: false
        })
        .then(({ code, data }) => {
          if (code === 200 && data) {
            recipeCategoryList.value = data.map(item =>
              g_i.apiDataFormat(item, g_i.recipe.recipeCategoryInfo)
            )
          }
          return { code, data }
        })
    }

    const setRecipeTasteOptions = _ => {
      return g_api.recipe
        .apiDictDropList({
          dictType: 'taste_style',
          showToast: false
        })
        .then(({ code, data }) => {
          if (code === 200 && data) {
            recipeTasteOptions.value = data
          }
          return { code, data }
        })
    }

    const setRecipeCookStyleOptions = _ => {
      return g_api.recipe
        .apiDictDropList({
          dictType: 'cook_style',
          showToast: false
        })
        .then(({ code, data }) => {
          if (code === 200 && data) {
            recipeCookStyleOptions.value = data
          }
          return { code, data }
        })
    }

    const setCountryList = _ => {
      return g_api.recipe
        .apiDictDropList({
          dictType: 'country',
          showToast: false
        })
        .then(({ code, data }) => {
          if (code === 200 && data) {
            countryList.value = data
          }
          return { code, data }
        })
    }

    const setRecipeWeightOptions = _ => {
      return g_api.recipe
        .apiDictDropList({
          dictType: 'cook_weight',
          showToast: false
        })
        .then(({ code, data }) => {
          if (code === 200 && data) {
            recipeWeightOptions.value = data
          }
          return { code, data }
        })
    }

    const setMaterialProcessDropList = _ => {
      return g_api.recipe
        .apiProcessDropList({
          showToast: false
        })
        .then(({ code, data }) => {
          if (code === 200 && data) {
            materialProcessDropList.value = data.map(item => ({
              ...item,
              value: item.id,
              label: item.name
            }))
          }
          return { code, data }
        })
    }

    return {
      recipeLibraryList,
      recipeFormulatingList,
      recipeCategoryList,
      recipeTempData,
      recipeTasteOptions,
      recipeCookStyleOptions,
      recipeWeightOptions,
      countryList,
      materialProcessDropList,
      setRecipeCategoryList,
      setRecipeTasteOptions,
      setRecipeCookStyleOptions,
      setCountryList,
      setRecipeWeightOptions,
      setMaterialProcessDropList,
      startCipeScheduler
    }
  },
  {
    // persist: true // 配置持久化
    persist: [
      {
        key: 'recipe-store', // 自定义存储键名
        // storage: localStorage, // 默认是 localStorage,可以改为 sessionStorage,可全局配置
        pick: [
          'recipeLibraryList',
          'recipeFormulatingList',
          'recipeCategoryList',
          'recipeTempData',
          'recipeTasteOptions',
          'recipeCookStyleOptions',
          'recipeWeightOptions',
          'materialProcessDropList'
        ]
      }
    ]
  }
)

export function useOutsideRecipeStore() {
  return useRecipeStore(g_store)
}
